package com.cari.oa.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.cari.oa.domain.SoftModuleEntity;
import com.cari.oa.domain.SoftProjectEntity;
import com.cari.oa.domain.SysDictItemEntity;
import com.cari.oa.service.SoftBugService;
import com.cari.oa.service.SoftModuleService;
import com.cari.oa.service.SoftProjectService;
import com.cari.oa.service.SysDictItemService;
import com.cari.oa.util.Contants;
import com.cari.oa.util.StrUtils;
import com.cari.oa.util.Utils;

/**
* Title: SoftModuleController
* Description: 软件模块控制器
* Company: cari 
* @author    hjx 
* @date       2013-1-29
*/
@Controller
@SessionAttributes("username")
public class SoftModuleController {

	@Resource
	private SoftModuleService softModuleService;
	@Resource
	private SysDictItemService sysDictItemService;
	@Resource
	private SoftProjectService softProjectService;
	@Resource
	private SoftBugService softBugService;
	public static final String MODULE_NAME = "SOFTMODULE";
	
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(df, false));
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
    }
	
    @RequestMapping("soft/module/list.do")
    public String list(@ModelAttribute("username") String username,String name, String pId, String status,String projectId, Integer curPage, ModelMap modelMap) {
        if(curPage == null) curPage = 1;
        List<SysDictItemEntity> statusList = sysDictItemService.getItemsByGroupName("softModuleStatus");
		List<SoftProjectEntity>   projectList = softProjectService.getProjectListByEnname(username);
        Map<String, String> pNameMap = new HashMap<String, String>();
        SoftProjectEntity currProject = null;
        if(StrUtils.isEmpty(projectId) && projectList.size() > 0)
        {
        	currProject = projectList.get(0);
        	projectId = currProject.getId(); 
        }
        else
        {
        	for(SoftProjectEntity curr : projectList)
        	{
        		if(curr.getId().equals(projectId))
        		{
        			currProject = curr;
        			break;
        		}
        	}
        }
        long totalRecords = softModuleService.getCount(name, pId, status,projectId);
        long totalPage = totalRecords / Contants.PAGE_SIZE + (totalRecords % Contants.PAGE_SIZE != 0 ? 1 : 0);
        List<SoftModuleEntity> moduleList = softModuleService.getPage(name, pId, status, projectId, curPage, Contants.PAGE_SIZE);
        List<SoftModuleEntity> allList = softModuleService.getModuleByProjectId(projectId);
        List<String> treeList = softModuleService.getTree(false,projectId);  
        for (SoftModuleEntity m : allList) {
        	pNameMap.put(m.getId(), m.getName());
		}
        modelMap.addAttribute("treeList", treeList);
        modelMap.addAttribute("projectList", projectList);
        modelMap.addAttribute("pNameMap", pNameMap);
        modelMap.addAttribute("moduleList", moduleList);
        modelMap.addAttribute("statusList", statusList);
        modelMap.addAttribute("curPage", curPage);
        modelMap.addAttribute("totalPage", totalPage);
        modelMap.addAttribute("totalRecords", totalRecords);
        modelMap.addAttribute("name", name);
        modelMap.addAttribute("currProject", currProject);
        modelMap.addAttribute("pId", pId);
        modelMap.addAttribute("status", status);
        return "soft/module/list";
    }
    
    @RequestMapping(value = "soft/module/insert.do", method = RequestMethod.GET)
    public String enterInsert(String qs,String projectId, ModelMap modelMap) {
        List<SysDictItemEntity> statusList = sysDictItemService.getItemsByGroupName("softModuleStatus");
        List<SoftProjectEntity> projectList = softProjectService.getByStatus();
        String [] ids = projectId.split(",");
        List<String> treeList = softModuleService.getTree(true,ids[0]);      
    	modelMap.addAttribute("treeList", treeList);
    	modelMap.addAttribute("statusList", statusList);
        modelMap.addAttribute("projectList", projectList);
        modelMap.addAttribute("projectId", ids[0]);
        modelMap.addAttribute("qs", qs);
        return "soft/module/insert";
    }
    
    @RequestMapping(value = "soft/module/insert.do", method = RequestMethod.POST)
    @ResponseBody
    public String postInsert(@ModelAttribute("username") String username, @Valid SoftModuleEntity softModuleEntity, BindingResult result) {
        if(result.hasFieldErrors())
            return Utils.errorJsonResp(result.getFieldError().getDefaultMessage());
        String moduleName = softModuleEntity.getName();
        moduleName = moduleName.replace(" " ,"").trim();
        softModuleEntity.setName(moduleName);
        if (softModuleService.existByEnname(moduleName,softModuleEntity.getProjectId()))
            return Utils.errorJsonResp("名称已存在");
        if(softModuleEntity.getpId()!=null){
	        SoftModuleEntity module = softModuleService.getById(softModuleEntity.getpId());
	        if(module == null )
	        {
	        	return Utils.errorJsonResp("所选父模块不存在！");
	        }
        }
        softModuleService.insert(softModuleEntity);
        SysOperLogController.addOperLog(username, MODULE_NAME, "新增软件模块" + softModuleEntity.getName());
        return Utils.normalJsonResp();
    }
    
    @RequestMapping(value = "soft/module/view.do", method = RequestMethod.GET)
    public String enterView(String id, ModelMap modelMap) {
    	SoftModuleEntity module = softModuleService.getById(id);
    	List<SysDictItemEntity> statusList = sysDictItemService.getItemsByGroupName("softModuleStatus");
        List<SoftProjectEntity> projectList = softProjectService.getAll();
    	if(StrUtils.isNotEmpty(module.getpId())){
    	    SoftModuleEntity pModule = softModuleService.getById(module.getpId());
            modelMap.addAttribute("pName", pModule.getName());
    	}
    	modelMap.addAttribute("statusList", statusList);
        modelMap.addAttribute("projectList", projectList);
        modelMap.addAttribute("module", module);
        return "soft/module/view";
    }
    
    @RequestMapping(value = "soft/module/edit.do", method = RequestMethod.GET)
    public String enterEdit(String id, String qs,String projectId, ModelMap modelMap) {
	    List<SysDictItemEntity> statusList = sysDictItemService.getItemsByGroupName("softModuleStatus");
        List<SoftProjectEntity> projectList = softProjectService.getAll();
        String [] ids = projectId.split(",");
        List<String> treeList = softModuleService.getTree(true,ids[0]);         
    	modelMap.addAttribute("treeList", treeList);
        SoftModuleEntity  module = softModuleService.getById(id);
        modelMap.addAttribute("statusList", statusList);
        modelMap.addAttribute("module", module);
        modelMap.addAttribute("projectList", projectList);
        modelMap.addAttribute("projectId", ids[0]);
        modelMap.addAttribute("qs", qs);
        return "soft/module/edit";
    }
    
    @RequestMapping(value = "soft/module/edit.do", method = RequestMethod.POST)
    @ResponseBody
    public String postEdit(@ModelAttribute("username") String username, @Valid SoftModuleEntity softModuleEntity,String oldName, BindingResult result) {
    	try{
            if(result.hasFieldErrors())
                return Utils.errorJsonResp(result.getFieldError().getDefaultMessage());
            if(!oldName.equals(softModuleEntity.getName()))
            {
            	 String moduleName = softModuleEntity.getName();
                 moduleName = moduleName.replace(" " ,"").trim();
                 softModuleEntity.setName(moduleName);
                 if (softModuleService.existByEnname(moduleName,softModuleEntity.getProjectId()))
                     return Utils.errorJsonResp("名称已存在");
            }
            if(softModuleEntity.getId().equals(softModuleEntity.getpId()))
            	return Utils.errorJsonResp("不能选择自己为父模块！");
            List<String> childIds = softModuleService.getByPId(softModuleEntity.getId());
            for(String id: childIds)
            {
            	if(id.equals(softModuleEntity.getpId()))
            	{
            	  	return Utils.errorJsonResp("所选父模块不能是原来的子模块！");
            	}
            }
            softModuleService.update(softModuleEntity);
    	}catch(Exception e)
    	{
    		e.printStackTrace();
    	}
        SysOperLogController.addOperLog(username, MODULE_NAME, "修改软件模块" + softModuleEntity.getName());
        return Utils.normalJsonResp();
    }
    
    @RequestMapping(value = "soft/module/delete.do")
    @ResponseBody
    public String postDelete(@ModelAttribute("username") String username, String id) {
    	SoftModuleEntity softModulentity = softModuleService.getById(id);
        if(softModulentity == null) 
        	return Utils.errorJsonResp("该模块已不存在，请刷新页面");
	    if(!softBugService.getByModuleId(id))
	    {
	    	return Utils.errorJsonResp("该模块已经在其他地方使用，不能删除！");
	    }
        List<String> childIds = softModuleService.getByPId(id);
        if(childIds == null || childIds.size()>0) 
        	return Utils.errorJsonResp("该模块已包含子模块，请先删除子模块");
        softModuleService.deleteById(id);
        SysOperLogController.addOperLog(username, MODULE_NAME, "删除字典项" + softModulentity.getName());
        return Utils.normalJsonResp();
    }
}
